﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using EOSCRM.Util ;
using EOSCRM.Domain;
using EOSCRM.Web.Common;
using EOSCRM.Dao;
using EOSCRM.Web.Shared;
using EOSCRM.Web.UserControls;


namespace EOSCRM.Web.Forms.DanhMuc
{
    public partial class NhanVien : Authentication
    {
        private readonly NhanVienDao _objDao = new NhanVienDao();
        private readonly LoDao _loDao = new LoDao();
        private readonly LoaiNVDao _loaiNVDao = new LoaiNVDao();
        private readonly LoaiLuongDao _loaiLuongDao = new LoaiLuongDao();
        private readonly KhuVucDao _khuVucDao = new KhuVucDao();

        private string CreateID()
        {
            string ma = "";
            ma = ma + "NV";
            ma = ma + DateTime.Now.Day.ToString("D2") + DateTime.Now.Month.ToString("D2") + DateTime.Now.Year.ToString("D4") + DateTime.Now.Hour.ToString("D2") + DateTime.Now.Minute.ToString("D2") + DateTime.Now.Second.ToString("D2");
            return ma;
        }
        private NHANVIEN ItemObj
        {
            get
            {
                if (!ValidateData())
                    return null;

                var kv = new NHANVIEN
                {
                    MaLo = ddlLo.SelectedValue,
                    MaNV = txtMaNV.Text.Trim(),
                    TenNV = txtTenNV.Text.Trim(),
                    GioiTinh=rdYes.Checked,
                    LoaiNV = ddlLoaiNV.SelectedValue,
                    LoaiLuong = ddlLoaiLuong.SelectedValue,
                    DiaChi = txtDiaChi.Text.Trim(),
                    CMND = txtcmnd.Text.Trim(),
                    MucLuong = int.Parse(txtluong.Text.Trim()),
                    NgaySinh = ConvertUtil.ToDateTime(txtngaysinh.Text.Trim()).Value,
                    NgayVaoLam = ConvertUtil.ToDateTime(txtngayvaolam.Text.Trim()).Value
                };
                kv.TinhTrang = ConvertUtil.ToInteger(ddltinhTrang.SelectedValue);
                if (ddltinhTrang.SelectedValue == "1")
                    kv.NgayNghi = DateTime.Now;
                return kv;
            }
        }

        private Mode UpdateMode
        {
            get
            {
                try
                {
                    if (Session[SessionKey.MODE] != null)
                    {
                        var mode = Convert.ToInt32(Session[SessionKey.MODE]);
                        return (mode == Mode.Update.GetHashCode()) ? Mode.Update : Mode.Create;
                    }

                    return Mode.Create;
                }
                catch (Exception)
                {
                    return Mode.Create;
                }
            }
            set
            {
                Session[SessionKey.MODE] = value.GetHashCode();
            }
        }



        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    ClearForm();
                    LoadKhuVuc();
                    LoadLo(ddlKhuVuc.SelectedValue);
                    LoadNVLo(ddlLo.SelectedValue);
                    LoadNvTheoLo(ddlLo.SelectedValue);
                    LoadLoaiNV();
                    LoadLoaiLuong();
                    upnlGrid.Update();
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }
        
        private void BindDataForGrid()
        {
            var objList = _objDao.GetList();
            gvList.DataSource = objList;
            gvList.PagerInforText = objList.Count.ToString();
            gvList.DataBind();
        }
        
        public bool ValidateData()
        {
            if (ddlLo.SelectedIndex == -1)
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Chọn lô"), ddlLo.ClientID);
                return false;
            }

            if (string.Empty.Equals(txtMaNV.Text))
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Mã nhân viên"), txtMaNV.ClientID);
                return false;
            }

            if (string.Empty.Equals(txtTenNV.Text))
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Tên nhân viên"), txtTenNV.ClientID);
                return false;
            }

            try
            {
                DateTime.Parse(txtngaysinh.Text.Trim());
            }
            catch (Exception)
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Ngày sinh"), txtngaysinh.ClientID);
                return false;
            }

            try
            {
                DateTime.Parse(txtngayvaolam.Text.Trim());
            }
            catch (Exception)
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Ngày vào làm"), txtngayvaolam.ClientID);
                return false;
            }

            if (string.Empty.Equals(txtDiaChi.Text))
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Địa chi"), txtDiaChi.ClientID);
                return false;
            }
            try
            {
                int.Parse(txtluong.Text.Trim());
            }
            catch (Exception)
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Mức lương"), txtluong.ClientID);
                return false;
            }
            return true;
        }

        private void DeleteList()
        {
            try
            {
                // Get list of ids that to be update
                var strIds = Request["listIds"];
                if ((strIds != null) && (!string.Empty.Equals(strIds)))
                {
                    //TODO: check relation before update list

                    var objs = new List<NHANVIEN>();
                    var listIds = strIds.Split(',');

                    // Kiem tra relation ship truoc khi delete
                    foreach (var ma in listIds)
                    {
                        if (_objDao.IsInUse(ma))
                        {
                            var msgIsInUse = new Message(MessageConstants.E_OBJECT_IN_USED, MessageType.Info, "nhân viên với mã", ma);

                            CloseWaitingDialog();

                            ShowError(ResourceLabel.Get(msgIsInUse));
                            return;
                        }
                    }

                    //Add ma vao danh sách cần delete
                    objs.AddRange(listIds.Select(ma => _objDao.Get(ma)));

                    if (objs.Count > 0)
                    {
                        var msg = _objDao.DeleteList(objs);
                        if (msg != null)
                        {
                            CloseWaitingDialog();

                            switch (msg.MsgType)
                            {
                                case MessageType.Error:
                                    ShowError(ResourceLabel.Get(msg));
                                    break;

                                case MessageType.Info:
                                    ShowInfor(ResourceLabel.Get(msg));
                                    break;

                                case MessageType.Warning:
                                    ShowWarning(ResourceLabel.Get(msg));
                                    break;
                            }
                        }
                    }
                    else
                    {
                        CloseWaitingDialog();
                    }
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        private void ClearForm()
        {
            txtMaNV.Text = CreateID();
            txtMaNV.ReadOnly = false;
            txtTenNV.Text = "";
            txtcmnd.Text = "";
            txtDiaChi.Text = "";
            txtluong.Text = "";
            txtngaysinh.Text = DateTime.Now.Day.ToString("D2") + "/" + DateTime.Now.Month.ToString("D2") + "/" + DateTime.Now.Year.ToString("D4");
            txtngayvaolam.Text = DateTime.Now.Day.ToString("D2") + "/" + DateTime.Now.Month.ToString("D2") + "/" + DateTime.Now.Year.ToString("D4");
           
            UpdateMode = Mode.Create;
            txtMaNV.Focus();
        }

        private void BindKhuVuc(NHANVIEN obj)
        {
            if (obj == null)
                return;
            SetControlValue(txtMaNV.ClientID, obj.MaNV);
            SetReadonly(txtMaNV.ClientID, true);
            SetControlValue(txtTenNV.ClientID, obj.TenNV);
            SetControlValue(txtDiaChi.ClientID, obj.DiaChi);
            SetControlValue(txtngaysinh.ClientID, obj.NgaySinh.ToString());
            SetControlValue(txtngayvaolam.ClientID, obj.NgayVaoLam.ToString());
            SetControlValue(txtcmnd.ClientID, obj.CMND);
            SetControlValue(txtluong.ClientID, obj.MucLuong.ToString());
            ddlLoaiLuong.SelectedValue = obj.LoaiLuong;
            ddlLoaiNV.SelectedValue = obj.LoaiNV;
            
            ddlNVQuanly.SelectedValue = obj.MaNVQuanLy;
            LoadNvTheoLo(ddlLo.SelectedValue);

            if (obj.GioiTinh == true)
            {
                rdYes.Checked = true;
                rdNo.Checked = false;
            }
            else
            {
                rdNo.Checked = true;
                rdYes.Checked = false;
            }
            ddltinhTrang.SelectedValue = obj.TinhTrang.HasValue ? obj.TinhTrang.Value.ToString() : "1";
            upnlInfor.Update(); 
        }
        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var makv = e.CommandArgument.ToString();

                switch (e.CommandName)
                {
                    case "EditItem":
                        if (!string.Empty.Equals(makv))
                        {
                            var objDb = _objDao.Get(makv);
                            if (objDb != null)
                            {
                                BindKhuVuc(objDb);
                                UpdateMode = Mode.Update;
                            }
                        }

                        CloseWaitingDialog();

                        break;
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var info = ItemObj;
            if (info == null)
            {
                CloseWaitingDialog();
                return;
            }

            if (ddlNVQuanly.SelectedIndex != -1)
            {
                if (ckKoQuanLy.Checked == false)
                {
                    info.MaNVQuanLy = ddlNVQuanly.SelectedValue;
                }
                else
                {
                    info.MaNVQuanLy = null;
                }
            }
            else
            {
                info.MaNVQuanLy = null;
            }

            Message msg;

            // insert new
            if (UpdateMode == Mode.Create)
            {
                if (!HasInsertPermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                } 

                var tontai = _objDao.Get(txtMaNV.Text.Trim());
                if (tontai != null)
                {
                    CloseWaitingDialog();
                    ShowError("Mã nhân viên đã tồn tại", txtMaNV.ClientID);
                    return;
                }
                
                msg = _objDao.Insert(info);
            }
            // update
            else
            {
                if (!HasUpdatePermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                } 
                msg = _objDao.Update(info);
            }

            CloseWaitingDialog();

            if (msg == null) return;

            if (msg.MsgType != MessageType.Error)
            {
                ShowInfor(ResourceLabel.Get(msg));

                ClearForm();

                // Refresh grid view
                LoadNVLo(ddlLo.SelectedValue);
                
                upnlGrid.Update();
            }
            else
            {
                ShowError(ResourceLabel.Get(msg));
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                // Authenticate
                if (!HasDeletePermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }

                DeleteList();
                LoadNVLo(ddlLo.SelectedValue);
                upnlGrid.Update();

                CloseWaitingDialog();
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseWaitingDialog();
            ClearForm();
        }

        private void LoadKhuVuc()
        {
            var objList = _khuVucDao.GetList();
            CommonFunc.BindDropDownList(ddlKhuVuc, objList, "TenKhuVuc", "MaKhuVuc", false);
        }
        private void LoadLoaiNV()
        {
            var objList = _loaiNVDao.GetList();
            CommonFunc.BindDropDownList(ddlLoaiNV, objList, "TenLoaiNV", "MaLoaiNV", false);
        }
        private void LoadLoaiLuong()
        {
            var objList = _loaiLuongDao.GetList();
            CommonFunc.BindDropDownList(ddlLoaiLuong, objList, "TenLoaiLuong", "MaLoaiLuong", false);
        }
        private void LoadLo(string makv)
        {
            var objList = _loDao.GetListKhuVuc(makv);
            CommonFunc.BindDropDownList(ddlLo, objList, "TenLo", "MaLo", false);
        }
        private void LoadNVLo(string ma)
        {
            var objList = _objDao.GetListLo(ma);            
            gvList.DataSource = objList;
            gvList.PagerInforText = objList.Count.ToString();
            gvList.DataBind();
        }
        private void LoadNvTheoLo(string ma)
        {
            var objList = _objDao.GetListLo(ma);
            CommonFunc.BindDropDownList(ddlNVQuanly, objList, "TenNV", "MaNV", false);

            if (ddlNVQuanly.Items.Count == 0)
            {
                ckKoQuanLy.Checked = true;
            }
            else
            {
                ckKoQuanLy.Checked = false;
            }
        }

        protected void ddlKhuVuc_SelectedIndexChanged1(object sender, EventArgs e)
        {
            ClearForm();
            ddlNVQuanly.Items.Clear();
            LoadLo(ddlKhuVuc.SelectedValue);
            LoadNVLo(ddlLo.SelectedValue);
            LoadNvTheoLo(ddlLo.SelectedValue);
            upnlGrid.Update();
        }

        protected void ddlLo_SelectedIndexChanged1(object sender, EventArgs e)
        {
            ClearForm();
            ddlNVQuanly.Items.Clear();
            LoadNVLo(ddlLo.SelectedValue);
            LoadNvTheoLo(ddlLo.SelectedValue);

            upnlGrid.Update();
            
        }

        protected void ckKoQuanLy_CheckedChanged(object sender, EventArgs e)
        {

        }

        public string CheckGioiTinh(object obj)
        {
            bool b = bool.Parse(obj.ToString());
            if (b)
                return "Nam.";
            else
                return "Nữ.";
        } 
    }
}